package com.tairan.chapter.flowable.service.impl;

import com.tairan.chapter.flowable.service.ReProcDefService;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.Map;

@Service
@Transactional(readOnly = true)
public class ReProcDefServiceImpl implements ReProcDefService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private IdentityService identityService;
    /**
     * 读取资源，通过部署ID
     * @param procDefId 流程定义ID
     * @param proInsId 流程实例ID
     * @param resType 资源类型(xml|image)
     * @return
     * @throws Exception
     */
    @Override
    public InputStream resourceRead(String procDefId, String proInsId, String resType) throws Exception {
        if (StringUtils.isBlank(procDefId)) {
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(proInsId).singleResult();
            procDefId = processInstance.getProcessDefinitionId();
        }
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(procDefId).singleResult();
        String resourceName = "";
        if ("image".equals(resType)) {
            resourceName = processDefinition.getDiagramResourceName();
        } else if ("xml".equals(resType)) {
            resourceName = processDefinition.getResourceName();
        }
        InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinition.getDeploymentId(), resourceName);

        return resourceAsStream;
    }

    @Override
    @Transactional
    public String startProcess(String procDefKey, String businessTable, String businessId, Map<String, Object> vars) {
        identityService.setAuthenticatedUserId("litairan");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(procDefKey, businessTable + ":" + businessId, vars);
        return processInstance.getId();
    }
}
